import React, { useState, useEffect, useRef } from 'react'
import { Popconfirm, Radio, Image, Button, Tag, Modal, Form, Input } from 'antd';
import { connect } from 'dva';
import { ProTable } from '@ant-design/pro-components';
import { getFilePrefix } from 'config'
import { CheckCircleOutlined, CloseCircleOutlined, ExclamationCircleOutlined } from '@ant-design/icons';

const UserManage = ({ userList, dispatch }) => {
  useEffect(() => {
    tableRef.current?.reload()// 刷新表格
  }, [userList])
  const tableRef = useRef();
  const addForm = useRef();
  const [reviewForm] = Form.useForm();
  const [userData, setUserData] = useState([])
  const [isModal, setIsModal] = useState(false)// 控制弹窗显与隐
  const [isReview, setIsReview] = useState(false)// 控制弹窗显与隐
  const statusFilters = [
    { text: '正常', value: 0 },
    { text: '封禁中', value: 1 },
    { text: '待审核', value: 2 },
    { text: '不通过', value: 3 },
  ];

  const viewStatus = ({ status }) => {
    switch (status) {
      case 0:
        return <Tag key="normal" icon={<CheckCircleOutlined />} color='success'>正常</Tag>;
      case 1:
        return <Tag key="baned" icon={<CloseCircleOutlined />} color='error'>封禁中</Tag>;
      case 3:
        return <Tag key="baned" icon={<CloseCircleOutlined />} color='error'>不通过</Tag>;
      default:
        return <Tag key="waitReview" icon={<ExclamationCircleOutlined />} color='warning'>待审核</Tag>;
    }
  }
  const columns = [
    {
      title: '用户id', dataIndex: 'userId', key: 'userId', align: 'center', search: false,
      sorter: (a, b) => a.userId - b.userId,
    },
    { title: '用户账户', dataIndex: 'account', key: 'account', align: 'center', },
    {
      title: '用户头像', dataIndex: 'imgFilePath', search: false, align: 'center',
      render: (_, record) => {
        if (!record.imgFilePath || record.imgFilePath === '') {
          return '-';
        }
        // let randomId = Math.random();
        const imgSrc = getFilePrefix() + record.imgFilePath // + "?random" + randomId;
        return <Image width='45px' style={{ background: 'transparent' }}
          src={imgSrc}
        />
      }
    },
    { title: '用户昵称', dataIndex: 'displayName', key: 'displayName', align: 'center', },
    { title: '用户名称', dataIndex: 'realName', key: 'realName', align: 'center', },
    { title: '学校', dataIndex: 'school', key: 'school', align: 'center', },
    { title: '学院', dataIndex: 'college', key: 'college', align: 'center', },
    { title: '班级', dataIndex: 'class', key: 'class', align: 'center', },
    { title: '注册时间', dataIndex: 'createTime', key: 'createTime', align: 'center', search: false, },
    {
      title: '用户状态', dataIndex: 'status', key: 'status', align: 'center', search: false,
      sorter: (a, b) => a.status - b.status,
      filters: statusFilters,
      onFilter: (value, record) => record.status === value,
      render: (_, record) => viewStatus(record)
    },
    {
      title: '操作', key: 'userInfo', align: 'center', search: false,
      render: (_, data) => {
        return (
          <>
            {data.status !== 3 ? <>{data.status === 2 ? <Button type='link' key="reviewUser" onClick={() => {
              setUserData(data); setIsReview(true);
            }}>审核账户</Button> : <>{data.status === 0 ?
              <Button type='link' key="banUser" onClick={() => {
                modifyStatus({ ...data, status: 1 });
              }}>封禁账户</Button> :
              <Button type='link' key="unbanUser" onClick={() => {
                modifyStatus({ ...data, status: 0 });
              }}>解除封禁</Button>}
              <Popconfirm title="确定要重置该用户密码吗?" onConfirm={() => {
                dispatch({
                  type: 'userManage/resetPwd',
                  payload: {
                    userId: data.userId,
                  },
                })
              }} okText="确定" cancelText="取消"><Button type='link' key="reset" >重置密码</Button>
              </Popconfirm></>}</> :
              <Popconfirm key="deleteUser" title="确定要删除该用户吗？" onConfirm={() => {
                dispatch({
                  type: 'userManage/delUser',
                  payload: {
                    userId: data.userId,
                  },
                })
              }} okText="确定" cancelText="取消">
                <Button danger type='link' key="delete" >删除</Button>
              </Popconfirm>}
          </>
        );
      }
    },
  ];

  const addUser = (data) => {
    dispatch({
      type: 'userManage/addUser',
      payload: {
        ...data,
      },
    })
    setIsModal(false)
  }

  const modifyStatus = (values) => {
    const userId = values.userId ? values.userId : userData.userId;
    dispatch({
      type: 'userManage/updateUserStatus',
      payload: {
        userId: userId,
        status: values.status,
      },
    });
    setIsReview(false);
    setUserData([]);
    reviewForm.resetFields();
  }

  const reloadTable = () => {
    dispatch({
      type: 'userManage/queryUser',
    })
  }


  return <>
    <ProTable actionRef={tableRef} defaultData={userList} columns={columns} rowKey="userList"
      pagination={{
        defaultPageSize: 10, // 默认每页显示10条数据
        showSizeChanger: true, // 显示每页显示条数的选择器
        pageSizeOptions: ['10', '20', '50'], // 可供用户选择的每页显示条数选项
      }}
      options={{ reload: reloadTable, setting: true, density: true, }}
      toolBarRender={() => [<Button type="primary" onClick={() => { setIsModal(true) }}>新建</Button>]}
      request={(params, sort, filter) => {
        return Promise.resolve({
          data: () => {
            return userList?.filter((item) => {
              let result = true;
              Object.entries(params).forEach(([key, value]) => {
                if (key == "current" || key == "pageSize") {
                  return;
                }
                const dataKey = key.replace("search", "")
                if (item.hasOwnProperty(dataKey)) {
                  result = (result && item[dataKey].indexOf(value) != -1)
                }
              })
              return result;
            });
          },
          success: true,
        });
      }} />;
    <Modal key="reviewUser" title="用户审核" open={isReview} onCancel={() => {
      setUserData([]); setIsReview(false); reviewForm.resetFields();
    }} maskClosable={false}
      footer={[
        <Button key="submit" type="primary" onClick={() => reviewForm?.submit()}>确定</Button>,
        <Button key="back" onClick={() => { setUserData([]); setIsReview(false); reviewForm.resetFields(); }}>取消</Button>
      ]}>
      <Form form={reviewForm} name="basic" labelCol={{ span: 8, }}
        wrapperCol={{ span: 24, }} style={{ width: "80%" }} onFinish={modifyStatus}>
        <Form.Item label="用户id" name="userId">{userData.userId}</Form.Item>
        <Form.Item label="账号" name="account">{userData.account}</Form.Item>
        <Form.Item label="网络昵称" name="displayName">{userData.displayName}</Form.Item>
        <Form.Item label="注册时间" name="createTime">{userData.createTime}</Form.Item>
        <Form.Item label="审核意见" name='status' rules={[{ required: true, message: '请选择审核意见' }]}>
          <Radio.Group options={[{ label: "通过", value: 0 }, { label: "不通过", value: 3 }]} />
        </Form.Item>
      </Form>
    </Modal >
    <Modal key="addUser" title="新增" open={isModal} onCancel={() => { setIsModal(false) }} maskClosable={false}
      footer={[
        <Button key="submit" type="primary" onClick={() => addForm.current?.submit()}>提交</Button>,
        <Button key="back" onClick={() => { setIsModal(false) }}>取消</Button>,
      ]}>
      <Form ref={addForm} name="basic" labelCol={{ span: 6, }} wrapperCol={{ span: 16, }} onFinish={addUser}>
        <Form.Item label="用户账号:" name="account" rules={[
          {
            required: true,
            message: '请输入您想添加的用户账号！',
          },
          {
            pattern: /^[A-Za-z0-9]+$/,
            message: '用户账号只能包含大小写字母和数字!',
          },
          {
            pattern: /^.{5,15}$/,
            message: '用户账号长度为5-15位!',
          }
        ]}>
          <Input /></Form.Item>
        <Form.Item label="用户密码:" name="Password" rules={[
          {
            required: true,
            message: '请输入用户密码！',
          },
          {
            pattern: /^[A-Za-z0-9!@#$%^&*()-_=+[\]{}|;:'",.<>?/]$/,
            message: '密码仅允许出现大小写字母、数字和特殊字符！',
          },
          {
            pattern: /^.{6,18}$/,
            message: '用户密码长度为6-18位!',
          },]}>
          <Input /></Form.Item>
        <Form.Item label="社交昵称:" name="displayName" rules={[
          {
            required: true,
            message: '请输入用户昵称！',
          },
          {
            pattern: /^.{1,10}$/,
            message: '用户昵称长度为1-10位!',
          },
          {
            pattern: /^[\u4e00-\u9fa5A-Za-z0-9]+$/,
            message: '用户昵称只能包含字母,数字和汉字!',
          },]}>
          <Input /></Form.Item>
      </Form>
    </Modal>{
    }
  </>
}

export default connect(({ userManage }) => ({
  userList: userManage.userList,
}))(UserManage);
